<template>
    <el-dialog v-model="visible" class="chat-dialog" title="大模型对话框" :style="{ height: '80vh', top: '-8vh' }"
        :modal-style="{ alignItems: 'center' }" width="60%">
        <div class="messages" ref="messageContainer">
            <div v-for="(msg, index) in messages" :key="index" class="message">
                <div :class="['message-content', msg.isUser ? 'user-message' : 'bot-message']">
                    <div v-html="marked.parse(msg.text)"></div>
                </div>
            </div>
        </div>
        <div v-if="isThinking" class="thinking">🤖 正在思考...</div>
        <template #footer>
            <form @submit.prevent="sendUserMessage" class="input-form">
                <input v-model="inputMessage" placeholder="输入消息..." class="input-box" />
                <button type="submit" class="send-button">发送</button>
            </form>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" name="ChatDialog">
import { ref, computed, watch, nextTick, onMounted } from 'vue';
import { sendStreamMessage, parseSSE } from '@/api/flow-api';
import { marked } from 'marked';
import { ElMessage } from 'element-plus';

const props = defineProps({
    id: {
        type: String,
        required: true,
    },
    modelValue: {
        type: Boolean,
        required: true
    },
    api: {
        type: Object,
        required: true
    }
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
});

const isThinking = ref(false);
const inputMessage = ref('');
const messages = ref<Array<{ text: string; isUser: boolean }>>([]);
const messageContainer = ref<HTMLDivElement | null>(null);
const autoScroll = ref(true);

watch(messages, async () => {
    if (autoScroll.value) {
        await nextTick();
        scrollToBottom();
    }
})

watch(visible, (isVisible) => {
    if (isVisible) {
        autoScroll.value = true;
        setTimeout(() => {
            scrollToBottom();
        }, 100);
    }
})

watch(
    () => props.id,
    (newId) => {
        messages.value = []
    }
)

onMounted(() => {
    if (messageContainer.value) {
        messageContainer.value.addEventListener('scroll', () => handleScroll);
    }
})

const handleScroll = () => {
    if (!messageContainer.value) return;

    const { scrollTop, scrollHeight, clientHeight } = messageContainer.value;
    const threshold = 50;
    autoScroll.value = scrollTop + clientHeight >= scrollHeight - threshold;
}

// 发送消息到后端
const sendUserMessage = async () => {

    const userMessage = inputMessage.value.trim();
    if (!userMessage) {
        ElMessage.error('请输入消息！')
        return;
    }
    isThinking.value = true;

    // 添加用户消息到聊天记录
    messages.value.push({ text: userMessage, isUser: true });
    inputMessage.value = '';
    autoScroll.value = true;
    await nextTick();
    scrollToBottom();

    // 添加一个空的机器人消息占位符
    messages.value.push({ text: '', isUser: false })

    try {
        const stream = await sendStreamMessage({
            id: props.id,
            message: userMessage
        })

        const reader = stream.getReader()
        const decoder = new TextDecoder()
        isThinking.value = false;

        let botReply = ''
        while (true) {
            const { done, value } = await reader.read()
            if (done) break

            const chunk = decoder.decode(value, { stream: true })
            console.log('接收到的数据:', chunk)
            try {
                for (const data of parseSSE(chunk)) {
                    botReply += data.message
                }
                const lastMessage = messages.value[messages.value.length - 1]
                lastMessage.text = botReply

                await nextTick()
                scrollToBottom()
            } catch (error) {
                console.error('解析SSE数据失败:', error)
                ElMessage.error('解析SSE数据失败: ' + error)
                isThinking.value = false;
            }
        }

    } catch (error) {
        console.error('流式请求失败:', error)
        ElMessage.error('请求失败，请稍后再试。')
        isThinking.value = false;
    }



};

// 自动滚动到底部
const scrollToBottom = () => {
    if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
};
</script>

<style scoped>
.chat-dialog {
    overflow: hidden;
    margin: 0 auto;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    padding: 10px;
    background-color: #f9f9f9;
}

/* .chat-dialog,
:deep(.chat-dialog .el-dialog__body),
.messages {
    border: 1px solid red;
} */

/* 重置 Element Plus 默认 body 样式 */
:deep(.chat-dialog .el-dialog__body) {
    display: flex;
    flex-direction: column;
    padding: 0;
    height: 100%;
    overflow: hidden;
}

.messages {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    height: 70vh;
    gap: 10px;
}

.message {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.message-content {
    padding: 10px;
    border-radius: 8px;
    max-width: 70%;
    word-wrap: break-word;
}

.user-message {
    align-self: flex-end;
    background-color: #dcf8c6;
    margin-left: auto;
}

.bot-message {
    align-self: flex-start;
    background-color: #ececec;
    margin-right: auto;
}

.input-form {
    flex-shrink: 0;
    display: flex;
    margin-top: 10px;
}

.input-box {
    flex: 1;
    padding: 10px;
    font-size: 14px;
}

.send-button {
    padding: 10px 20px;
    background-color: #42b983;
    color: white;
    border: none;
    cursor: pointer;
}

.send-button:hover {
    background-color: #379c6f;
}
</style>